import os
import sqlite3

class database :
	def __init__ ( self , db_file ) :
		self.db = sqlite3.connect ( db_file )
		self.cur = self.db.cursor ( )
	def add_table ( self , title , *points ) :
		column_def = "id INTEGER PRIMARY KEY"
		for name , type in points :
			column_def = " , ".join ( [ column_def , " ".join ( 
				[ name , type ] ) ] ) 
		self.cur.execute ( " ".join ( [ 'CREATE TABLE IF NOT EXISTS' , 
			title , '(' , column_def , ')' ] ) ) # cheating :(
		self.db.commit ( )
	def matches ( self , table_title , **points ) :
		expr = ""
		for column_name , value in points.iteritems ( ) :
			expr = " or ".join ( [ expr, " ".join ( [ column_name , '=' , 
				value ] ) ] )
		expr = expr.strip ( ' or ' ) # is there a better way?
		self.cur.execute ( " ".join ( [ 'SELECT id FROM' , table_title , 
			'WHERE' , expr ] ) )
		return self.cur.fetchall ( )
	def add_data ( self , table_title , **points ) :
		column_names , values = "" , ""
		for column_name , value in points.iteritems ( ) :
			column_names = " , ".join ( [ column_names , column_name ] )
			values = " , ".join ( [ values , value ] )
		column_names = column_names.strip ( ' ,' )
		values = values.strip ( ' ,' )
		self.cur.execute ( " ".join ( [ 'INSERT INTO' , table_title , '(' , 
			column_names , ')' , 'VALUES' , '(' , values , ')' ] ) )
		self.db.commit ( )
	def modify_data ( self , table_title , id , **points ) :
		data = ""
		for column_name , value in points.iteritems ( ) : 
			data = " , ".join ( [ data , "=".join ( [ column_name , 
				value ] ) ] ) 
		data = data.strip ( ' ,' )
		self.cur.execute ( " ".join ( [ 'UPDATE' , table_title , 'SET' , 
			data , 'WHERE id =' , id ] ) )
		self.db.commit ( )



		
